<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2017/6/5
 * Time: 15:42
 */

namespace frontend\controllers;

use common\models\ActivityLottery;
use common\models\ActivityMAdConfig;
use common\models\Category;
use common\models\Company;
use common\models\CompanyBanner;
use common\models\Goods;
use common\models\GoodsAttribute;
use common\models\GoodsAttributeValues;
use common\models\News;
use common\models\Order;
use common\models\OrderComment;
use common\models\OrderGoodsRelation;
use common\models\User;
use yii;

class ShopController extends PublicBaseController
{
    public $shelves_code;
    public $recovery_code;
    public $recommend_pass_code;
    public $comment_pass_code;
    public $comment_not_del_code;
    public $goods_recommend_code;
    public $company_open_code;
    public $municipality_arr;
    public $activity_open_code;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $this->shelves_code = 1;                    //0 下架    1 上架
        $this->recovery_code = 0;                   //是否被回收 0:未被回收 1:已被回收
        $this->recommend_pass_code = 2;             //推荐审核状态 0:未审核 1:审核中 2:审核通过 3:审核不通过
        $this->comment_pass_code = 1;
        $this->comment_not_del_code = 0;

        $this->company_open_code = 1;

        $this->activity_open_code = 1;            //活动开区code

        $this->municipality_arr = ['北京', '天津', '上海', '重庆'];
    }

    /**
     * 获取地址位置
     * @return array
     */
    public function actionGetCity(){
        $data = $this->_getCompanyDataByCity();

        if($data['prov'] == '北京'){
            $data['city'] = '北京';
        }

        $this->_successData($data);
    }

    /**
     * 获取公司列表
     * @return array
     */
    public function actionGetCompanyList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $size = isset($this->params['size']) ? $this->params['size'] : 10;

        $company_list = Company::find()
            ->select(['company_id', 'name', 'prov', 'city'])
            ->where(['status'=>$this->company_open_code])
            ->offset(($page - 1)*$size)
            ->limit($size)
            ->asArray()
            ->all();

        if(!empty($company_list)){
            foreach ($company_list as $key=>&$item){
                if($item['city']){
                    $item['fistchar'] = $this->_getfirstchar($item['city']);
                }

                //如果该公司下没有商品 则不显示
                $company_goods_count = Goods::find()->where(['company_id'=>$item['company_id']])->count();
                if ($company_goods_count == 0) {
                    unset($company_list[$key]);
                }
            }
            unset($item);

            /* 直辖市处理 */
            foreach ($company_list as &$company){
                if(in_array($company['prov'], $this->municipality_arr)){
                    $company['city'] = $company['prov'];
                }
            }
            unset($company);
        }


        $sort_list = [];
        foreach ($company_list as $item){
            if($item['fistchar'] == 'A'){$sort_list['A'][] = $item;}
            if($item['fistchar'] == 'B'){$sort_list['B'][] = $item;}
            if($item['fistchar'] == 'C'){$sort_list['C'][] = $item;}
            if($item['fistchar'] == 'D'){$sort_list['D'][] = $item;}
            if($item['fistchar'] == 'E'){$sort_list['E'][] = $item;}
            if($item['fistchar'] == 'F'){$sort_list['F'][] = $item;}
            if($item['fistchar'] == 'G'){$sort_list['G'][] = $item;}
            if($item['fistchar'] == 'H'){$sort_list['H'][] = $item;}
            if($item['fistchar'] == 'I'){$sort_list['I'][] = $item;}
            if($item['fistchar'] == 'J'){$sort_list['J'][] = $item;}
            if($item['fistchar'] == 'K'){$sort_list['K'][] = $item;}
            if($item['fistchar'] == 'L'){$sort_list['L'][] = $item;}
            if($item['fistchar'] == 'M'){$sort_list['M'][] = $item;}
            if($item['fistchar'] == 'N'){$sort_list['N'][] = $item;}
            if($item['fistchar'] == 'O'){$sort_list['O'][] = $item;}
            if($item['fistchar'] == 'P'){$sort_list['P'][] = $item;}
            if($item['fistchar'] == 'Q'){$sort_list['Q'][] = $item;}
            if($item['fistchar'] == 'R'){$sort_list['R'][] = $item;}
            if($item['fistchar'] == 'S'){$sort_list['S'][] = $item;}
            if($item['fistchar'] == 'T'){$sort_list['T'][] = $item;}
            if($item['fistchar'] == 'U'){$sort_list['U'][] = $item;}
            if($item['fistchar'] == 'V'){$sort_list['V'][] = $item;}
            if($item['fistchar'] == 'W'){$sort_list['W'][] = $item;}
            if($item['fistchar'] == 'X'){$sort_list['X'][] = $item;}
            if($item['fistchar'] == 'Y'){$sort_list['Y'][] = $item;}
            if($item['fistchar'] == 'Z'){$sort_list['Z'][] = $item;}
        }

        ksort($sort_list);
        $this->_successData($sort_list);
    }


    /**
     * 获取首页轮播图
     * @return array
     */
    public function actionGetBanners(){
        $company_id = yii::$app->request->post('company_id', 0);
        if(!$company_id){
            $company_data = $this->_getCompanyDataByCity();
            $company_id   = $company_data['company_id'];
        }

        $banners = CompanyBanner::find()
            ->select(['banner_id', 'banner_desc', 'banner_link', 'banner_img_url', 'is_global'])
            ->where("company_id = {$company_id} OR is_global = 1")
            ->orderBy('banner_sort ASC, is_global ASC')
            ->asArray()
            ->all();
        $banners || $banners = [];

        $this->_successData($banners);
    }

    /**
     * 获取活动信息
     */
    public function actionGetActivityLotteryInfo(){
        $company_id = yii::$app->request->post('company_id', 0);
        if(!$company_id) $this->_errorData('10000', '参数错误');

        /* 该公司下的活动 */
        $activity_lottery_info = ActivityLottery::find()
            ->select(['activity_id', 'title', 'cover_img', 'end_time'])
            ->where("company_id = {$company_id} AND status = {$this->activity_open_code}")
            ->asArray()->one();
        if(is_array($activity_lottery_info)){
            if(strtotime($activity_lottery_info['end_time']) < time()) $activity_lottery_info = [];
        }

        $this->_successData($activity_lottery_info);
    }

    /**
     * 获取所在城市分公司的商品列表
     * @param company_id
     * @param goods_name
     * @param page
     * @param size
     * @return array
     */
    public function actionGetGoodsList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $size = isset($this->params['size']) ? $this->params['size'] : 10;
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 1;
        $goods_name = isset($this->params['goods_name']) ? $this->params['goods_name'] : 0;
        $category_id = isset($this->params['category_id']) ? $this->params['category_id'] : 0;

        if(!$company_id){
            $company_data = $this->_getCompanyDataByCity();
            $company_id   = $company_data['company_id'];
        }
        if(!$company_id) $company_id = 1;

        $where = "is_shelves={$this->shelves_code} AND is_recovery={$this->recovery_code}";
//        $where = "is_shelves={$this->shelves_code} AND recommend_status={$this->recommend_pass_code} AND is_recovery={$this->recovery_code}";
        if($company_id){
            $where .= " AND company_id={$company_id}";
        }

        if($goods_name){
            $where .= " AND goods_name LIKE '%{$goods_name}%'";
        }

        $offset = ($page - 1) * $size;

        if($category_id){
            $goods_list = Goods::find()
                ->alias('g')
                ->leftJoin('vrshop.category_goods_relation c', 'g.goods_id=c.goods_id')
                ->where(['c.category_id'=>$category_id])
                ->andWhere("g.is_shelves = 1 AND g.is_recovery = 0")
                ->orderBy('g.create_time DESC')
                ->asArray()
                ->all();

            $total = Goods::find()
                ->alias('g')
                ->leftJoin('vrshop.category_goods_relation c', 'g.goods_id=c.goods_id')
                ->where(['c.category_id'=>$category_id])
                ->andWhere("g.is_shelves = 1 AND g.is_recovery = 0")
                ->orderBy('g.create_time DESC')
                ->asArray()
                ->count();
        }else{
            $goods_list = Goods::find()
                ->select(['goods_id', 'goods_name', 'tags', 'art_no', 'huiwenbi', 'market_price', 'banner_image', 'goods_stock', 'goods_introduce', 'recommend_status'])
                ->where($where)
                ->andWhere("is_shelves = 1 AND is_recovery = 0")
                ->offset($offset)
                ->limit($size)
                ->orderBy('create_time DESC')
                ->asArray()
                ->all();

            $total = Goods::find()
                ->where($where)
                ->andWhere("is_shelves = 1 AND is_recovery = 0")
                ->asArray()
                ->count();
        }

        /* 推荐在前 */
        $_list = false;
        $_recommend_list = false;

        foreach ($goods_list as $goods){
            if($goods['recommend_status'] == 2){
                $_recommend_list[] = $goods;
            }else{
                $_list[] = $goods;
            }
        }

        $_list || $_list = [];
        $_recommend_list || $_recommend_list = [];
        $goods_list = array_merge($_recommend_list, $_list);
        /* 推荐在前 END */

        $rerturn_data = ['total'=>$total, 'list'=>$goods_list];
        $this->_successData($rerturn_data);
    }

    /**
     * 推荐商品
     * 所有公司下推荐的商品  随机一件
     */
    public function actionGetOneRecommendGoods(){
        $all_recommend_goods_arr = Goods::find()->select(['goods_id'])->where(['recommend_status'=>$this->recommend_pass_code, 'is_recovery'=>$this->recovery_code])->asArray()->column();
        $recommend_goods_count   = count($all_recommend_goods_arr);
        if($recommend_goods_count >= 0) $this->_errorData('20000', '暂无推荐商品');
        $rand_goods_id = mt_rand(0, $recommend_goods_count - 1);
        $goods_id = $all_recommend_goods_arr[$rand_goods_id];

        $goods_info = Goods::find()->where(['goods_id'=>$goods_id])->asArray()->one();
        $this->_successData($goods_info);
    }

    /**
     * 商品详情
     * @goods_id
     * @company_id
     * @return array
     */
    public function actionGetGoodsInfo(){
        $goods_id = isset($this->params['goods_id']) ? $this->params['goods_id'] : 0;
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;

        if(!$goods_id || !$company_id) $this->_errorData('2000', '参数错误');

        $goods_info = Goods::findOne($goods_id)->toArray();

        if(!$goods_info || $goods_info['is_recovery'] == 1 || $goods_info['is_shelves'] == 0) $this->_errorData('2001', '商品信息有误');


//        $attr_list = GoodsAttributeValues::find()->where(['goods_id'=>$goods_info['goods_id']])->asArray()->all();
        $attr_list = GoodsAttribute::find()
            ->alias('ga')
            ->leftJoin('vrshop.goods_attribute_values gav', 'ga.attribute_id = gav.attribute_id')
            ->where(['gav.goods_id'=>$goods_info['goods_id']])
            ->groupBy('ga.attribute_id')
            ->asArray()->all();

        if($attr_list){
            foreach ($attr_list as &$item){
                $item['list'] = GoodsAttributeValues::find()->where(['attribute_id'=>$item['attribute_id'], 'goods_id'=>$goods_info['goods_id']])->asArray()->all();
            }
            unset($item);
        }

        $goods_info['attr_list'] = $attr_list;
        $this->_successData($goods_info);
    }

    /**
     * 商品评论列表
     * @goods_id
     * @company_id
     * @return array
     */
    public function actionGetGoodsComment(){
        $goods_id = isset($this->params['goods_id']) ? $this->params['goods_id'] : 0;
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $size = isset($this->params['size']) ? $this->params['size'] : 10;
        if(!$goods_id) $this->_errorData('2000', '参数错误');

        $return_data = OrderComment::GetGoodsCommentList($company_id, $goods_id, $this->comment_pass_code, $this->comment_not_del_code, $page, $size);
        $this->_successData($return_data);
    }

    /**
     * 获取分类列表
     */
    public function actionGetCategoryList(){
        $page       = isset($this->params['page']) ? $this->params['page'] : 1;
        $page_size  = isset($this->params['size']) ? $this->params['size'] : 10;
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $category_id = isset($this->params['category_id']) ? $this->params['category_id'] : 0;
        $category_name  = isset($this->params['category_name']) ? $this->params['category_name'] : '';
        $review_status  = isset($this->params['review_status']) ? $this->params['review_status']: 2;    //审核状态

        if(!$company_id){
            $this->_errorData('0001','参数错误');
        }

        $category_list = Category::GetList($company_id, $category_id, $category_name, $review_status, $page, $page_size);

        $this->_successData($category_list);
    }

    /**
     * M站活动配置
     */
    public function actionActivityConfigDetail(){
        $config_detail = ActivityMAdConfig::find()->where(['status'=>1])->asArray()->one();
        $config_detail || $config_detail = [];
        $this->_successData($config_detail);
    }

    /**
     * 根据用户IP判断城市，返回所在分公司的信息
     * @return array
     */
    protected function _getCompanyDataByCity(){
        $ip_addr = yii::$app->request->userIP;
        if($ip_addr == '' || $ip_addr == '127.0.0.1' || strpos($ip_addr, '192.168') !== false){
            $company_data = Company::findOne('1')->toArray();
        }else{
            $url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip_addr;
            $ip  = json_decode(file_get_contents($url), true);
            if($ip['code'] == '1'){
                $this->_errorData('8000', '获取地址位置出错');
            }
            $data = $ip['data'];
            if(strpos($data['region'], '市')) $data['province'] = strstr($ip['data']['region'], '市', true);
            if(strpos($data['city'], '市')) $data['city'] = strstr($ip['data']['city'], '市', true);
            if(strpos($data['region'], '省')) $data['province'] = strstr($ip['data']['city'], '省', true);
            if(strpos($data['city'], '省')) $data['city'] = strstr($ip['data']['city'], '省', true);
            $company_data = Company::find()->where(" status = {$this->company_open_code} AND city='{$data['city']}' OR prov='{$data['province']}'")->orderBy('create_time DESC')->asArray()->one();
        }

        return $company_data;
    }

    /**
     * @param $s0
     * @return int|string
     */
    protected function _getfirstchar($s0)
    {
        if (ord($s0) >= "1" and ord($s0) <= ord("z")) {
            return strtoupper($s0);
        }
        $s = iconv("UTF-8", "gb2312", $s0);               //如果需要转换为utf-8的话
        //$s = $s0;                                         //无需转换的情况
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 and $asc <= -20284) {
            return "A";
        }
        if ($asc >= -20283 and $asc <= -19776) return "B";
        if ($asc >= -19775 and $asc <= -19219) return "C";
        if ($asc >= -19218 and $asc <= -18711) return "D";
        if ($asc >= -18710 and $asc <= -18527) return "E";
        if ($asc >= -18526 and $asc <= -18240) return "F";
        if ($asc >= -18239 and $asc <= -17923) return "G";
        if ($asc >= -17922 and $asc <= -17418) return "H";
        if ($asc >= -17417 and $asc <= -16475) return "J";
        if ($asc >= -16474 and $asc <= -16213) return "K";
        if ($asc >= -16212 and $asc <= -15641) return "L";
        if ($asc >= -15640 and $asc <= -15166) return "M";
        if ($asc >= -15165 and $asc <= -14923) return "N";
        if ($asc >= -14922 and $asc <= -14915) return "O";
        if ($asc >= -14914 and $asc <= -14631) return "P";
        if ($asc >= -14630 and $asc <= -14150) return "Q";
        if ($asc >= -14149 and $asc <= -14091) return "R";
        if ($asc >= -14090 and $asc <= -13319) return "S";
        if ($asc >= -13318 and $asc <= -12839) return "T";
        if ($asc >= -12838 and $asc <= -12557) return "W";
        if ($asc >= -12556 and $asc <= -11848) return "X";
        if ($asc >= -11847 and $asc <= -11056) return "Y";
        if ($asc >= -11055 and $asc <= -10247) return "Z";
        return 0;
    }

    protected function _createOsn($user_id){
        $orderSn = date('Y')                            //获取年份对应的映射值
            . strtoupper(dechex(date('m')))            //月份
            . date('d')                                //日期
            . substr(time(), -5)                       //当前时间戳 截取后5位
            . substr(microtime(), 2, 5)                //当前微秒数 截取
            . substr($user_id, 5, 4);
        return $orderSn;
    }
}